package chapter7_取消关闭.停止基于线程的服务;

import java.io.File;
import java.io.FileFilter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 毒丸
 */
public class IndexingService {
    private static final File POISON = new File("");
    private final IndexerThread consumer = new IndexerThread();
    private final CrawlerThread producer = new CrawlerThread();
    private final BlockingQueue<File> queue = new LinkedBlockingQueue<>();
    private final FileFilter fileFilter = null;
    private final File root = new File("");

    class CrawlerThread extends Thread{
        @Override
        public void run() {
            try {
                crawl(root);
            } catch (InterruptedException e) {
            }
            finally {
                while (true) {
                    try {
                        //投放毒丸 :)
                        queue.put(POISON);
                        break;
                    } catch (InterruptedException e) {
                        //重新尝试
                    }
                }
            }
        }

        private void crawl(File root) throws InterruptedException {
        }
    }
    class IndexerThread extends Thread{
        @Override
        public void run() {
            try {
                while (true) {
                    File file = queue.take();
                    if (file == POISON) {
                        break;
                    } else {
//                        indexFile(file);
                    }
                }
            } catch (InterruptedException consumed){}
        }
    }

    public void start() {
        producer.start();
        consumer.start();
    }

    //结束时，一次调用stop&awaitTermination方法
    public void stop() {
        producer.interrupt();
    }

    public void awaitTermination() throws InterruptedException {
        consumer.join();
    }
}
